package com.hardson.toolkit.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class DESUtil {
    public static String createKey() {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 为我们选择的DES算法生成一个KeyGenerator对象
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        kg.init(sr);
        // 生成密钥
        SecretKey key = kg.generateKey();
        byte[] keyByte = key.getEncoded();
        StringBuilder buf = new StringBuilder();
        for (byte b : keyByte) {
            buf.append(b).append(",");
        }
        buf.deleteCharAt(buf.length() - 1);
        return buf.toString();
    }

    /**
     * 对数据以DES方式加密
     *
     * @param keyByte 密钥
     * @param source  要加密的数据
     * @return 用keyByte加密的数据
     * @throws GeneralSecurityException
     */
    public static byte[] encryptData(final byte[] keyByte, final byte[] source)
            throws GeneralSecurityException {
        // 产生一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(keyByte);
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        // Cipher 对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, key, sr);
        return cipher.doFinal(source);
    }

    /**
     * 对DES加密的数据进行解密
     *
     * @param keyData 密钥
     * @param source  以DES加密的数据
     * @return 解密的数据
     * @throws GeneralSecurityException
     */
    public static byte[] decryptData(final byte[] keyData, final byte[] source)
            throws GeneralSecurityException {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从密钥文件中获取原始密钥数据
        // 创建一个 DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(keyData);
        // 创建一个密钥工厂，然 后用它把DESKeySpec对象转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        // Cipher 对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密钥初始化Cipher对 象
        cipher.init(Cipher.DECRYPT_MODE, key, sr);
        // 获得经过加密的数据
        // 执行解密操作
        return cipher.doFinal(source);
    }
}
